// 结合视频，再学习
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

const int N = 1e5 + 5;
const int D = sqrt(1e9); // 阈值

int T, n, m, mod, a, b, x;

// 快速幂
ll qpow(ll base, ll exp) {
  ll res = 1;
  while (exp > 0) {
    if (exp & 1) {
      res = res * base % mod;
    }
    base = base * base % mod;
    exp >>= 1;
  }
  return res;
}

// 等比数列和：1 + r + r^2 + ... + r^(n-1)
pair<ll, ll> geo_sum(ll r, ll n) {
  if (n == 1) {
    return {1, r};
  }

  auto half = geo_sum(r, n / 2);
  ll s = half.first;
  ll p = half.second;

  if (n & 1) {
    ll new_s = ((s + s * p) % mod * r % mod + 1) % mod;
    ll new_p = p * p % mod * r % mod;
    return {new_s, new_p};
  } else {
    ll new_s = (s + s * p) % mod;
    ll new_p = p * p % mod;
    return {new_s, new_p};
  }
}

// 计算等比数列：x^s + x^(s+d) + ... + x^(s+(len-1)*d)
ll calc_series(int s, int d, int len) {
  if (d < 0) {
    return calc_series(s + (len - 1) * d, -d, len);
  }

  ll base_pow = qpow(x, s);
  ll ratio = qpow(x, d);
  auto sum = geo_sum(ratio, len);

  return base_pow * sum.first % mod;
}

// 寻找合适的步长
pair<int, int> find_step() {
  for (int i = 1;; i++) {
    ll step = (1LL * a * i) % m;

    if (step <= m / D) {
      return {i, step}; // 正小值
    }

    if (step >= m - m / D) {
      return {i, -(m - step)}; // 负小值
    }
  }
}

// 计算段长度
int seg_len(int idx, int step, int g) {
  int exp = (1LL * a * idx + b) % m;

  if (step >= 0) {
    if (step == 0) {
      return (n - idx + g - 1) / g;
    } else {
      return (m - exp + step - 1) / step;
    }
  } else {
    return exp / (-step) + 1;
  }
}

// 暴力计算
ll brute() {
  ll ans = 0;
  for (int i = 0; i < n; i++) {
    int e = (1LL * a * i + b) % m;
    ans = (ans + qpow(x, e)) % mod;
  }
  return ans;
}

// 优化算法
ll opt() {
  auto [g, step] = find_step();
  ll ans = 0;

  for (int i = 0; i < g; i++) {
    int idx = i;

    while (idx < n) {
      int len = seg_len(idx, step, g);

      if (idx + 1LL * len * g >= n) {
        len = (n - idx + g - 1) / g;
      }

      int s = (1LL * a * idx + b) % m;
      ans = (ans + calc_series(s, step, len)) % mod;

      idx += len * g;
    }
  }

  return ans;
}

int main() {
  freopen("g.in", "r", stdin);
  freopen("g.out", "w", stdout);

  cin >> T;
  while (T--) {
    cin >> n >> m >> a >> b >> x >> mod;

    ll ans;
    if (n <= D) {
      ans = brute();
    } else {
      ans = opt();
    }

    cout << (ans + mod) % mod << endl;
  }

  return 0;
}
